import { Component, OnInit } from '@angular/core';
import { getQueryString } from '@shared';
import { _HttpClient } from '@delon/theme';
import { NzNotificationService } from 'ng-zorro-antd';
import { SocialService, ITokenModel } from '@delon/auth';

/**
 * 第三方登录
 */
@Component({
  selector: 'app-third-login',
  template: `
    <div>载入中</div>
  `,
  providers: [SocialService],
})
export class ThirdLoginComponent implements OnInit {
  constructor(public http: _HttpClient, private notice: NzNotificationService, private socialService: SocialService) {}

  ngOnInit() {
    const url = window.location.href.replace('#/account/authredirect', '');
    const code = getQueryString(url, 'code');
    let state = getQueryString(url, 'state');
    const type = state.split('-')[1];
    state = state.split('-')[0];
    // 登录请求
    if (type === 'LOGIN') {
      const info: ITokenModel = { state, code, token: code };
      this.socialService.callback(info);
      window.close();
    } else if (type === 'BIND') {
      this.bind(state, code);
    }
  }

  bind(state, code) {
    this.http.post(`/cf/admin/social/bind?state=${state}&code=${code}`).subscribe(res => {
      this.notice.success('成功', '第三方账号绑定成功');
      window.close();
    });
  }
}
